#pragma once
#include<iostream> 
#include<unistd.h>
#include<cstring>


FILE* Mypopen(const char* cmd,const char* mod)
{
    if(strcmp(mod,"r") != 0) {

        return nullptr;
    }
   int pipe_fd[2];
   pid_t pid;
   FILE* fp = NULL;

   if(pipe(pipe_fd) == -1)
   {
     perror("create pipe fail") ;
     return nullptr;
   }

   pid = fork();
   if(pid < 0)
   {
    perror("fork fail");
    close(pipe_fd[0]);
    close(pipe_fd[1]);
    return nullptr;
   }

   if(pid == 0)
   {
     dup2(pipe_fd[1],STDOUT_FILENO);
     close(pipe_fd[0]);
    close(pipe_fd[1]);

    char* tmp[] = {const_cast<char*>(cmd),nullptr};
    execvp(cmd,tmp);

    perror("execvp fail");
   }
   else
   {
     close(pipe_fd[1]);
     fp = fdopen(pipe_fd[0],mod);
     if(fp == nullptr)
     {
        //
        return nullptr;
     }
   }
   return fp;
}

